//
//  ZhifuPass1ViewController.m
//  specialine
//
//  Created by 往返网络 on 17/7/19.
//  Copyright © 2017年 com. All rights reserved.
//

#import "ZhifuPass1ViewController.h" //发送验证码
#import "ZhifuPass2ViewController.h" //支付重置密码1
#import "PublicMethod.h"
#define return_tag 2000
#define send_tag 2001
#define next_tag 2002
//定义修改支付密码获取验证码URL
#define URL_ZHIFUGECODE [NSString stringWithFormat:@"%@/Appcustomernewer/Pay/paySetPwSendCode?type=get",BASE_URL]
@interface ZhifuPass1ViewController ()<UITextFieldDelegate>
//开辟多线程定时器，在后台执行，比NSTimer更自然
@property (nonatomic,strong) dispatch_source_t timer;
@property (nonatomic,strong)AFHTTPSessionManager * manger;

@end

@implementation ZhifuPass1ViewController
{
    UITextField * yanzhengtf;
    UIButton * resetyanzhengbtn;
    UIButton * nextbtn;
  
}
- (void)viewWillAppear:(BOOL)animated{
    
    self.navigationController.navigationBar.hidden = YES;
    
    self.tabBarController.tabBar.hidden = YES;
    
}
- (void)viewWillDisappear:(BOOL)animated{
    
    self.navigationController.navigationBar.hidden = NO;
    
    self.tabBarController.tabBar.hidden = NO;
}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self createUI];
    
    // Do any additional setup after loading the view.
}
- (void)createUI{
    
    self.view.backgroundColor = COLORRGBA(239, 239, 239, 1);
    
    UIView * titleview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 128.0/1334*SCREEN_H)];
    
    titleview.backgroundColor = COLORRGBA(7, 24, 57, 1);
    
    [self.view addSubview:titleview];
    
    float fontsize = 18;
    
    float corensize = 17;
    
    fontsize = SCREEN_H < 667 ? 16 : 20 ;
    
    corensize = SCREEN_H < 667 ? 15 : 19 ;
    
    if (SCREEN_H == 667) {
        fontsize = 18;
        corensize = 17;
    }
    
    UIButton * leftlable  = [[UIButton alloc]initWithFrame:CGRectMake(0, 20+14.0/1334*SCREEN_H, 80.0/W_BASE*SCREEN_W, 60.0/1334.0*SCREEN_H)];
    
    [leftlable setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    leftlable.titleLabel.font = [UIFont fontWithName:@"iconfont" size:fontsize+3];
    
    [leftlable setTitle:@"\U0000e697" forState:UIControlStateNormal];
    
    [leftlable.titleLabel setTextAlignment:NSTextAlignmentCenter];
    
    [leftlable addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    leftlable.tag = return_tag;
    [titleview addSubview:leftlable];
    
    UILabel * titlelab = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMinY(leftlable.frame), SCREEN_W, CGRectGetHeight(leftlable.frame))];
    
    titlelab.textAlignment = NSTextAlignmentCenter;
    
    titlelab.textColor = [UIColor whiteColor];
    
    titlelab.font = [UIFont systemFontOfSize:fontsize - 1];
    
    titlelab.text = @"重置支付密码";
    
    [titleview addSubview:titlelab];
    
    UILabel * phonelabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 128.0/H_BASE*SCREEN_H, SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    [self.view addSubview:phonelabel];
    phonelabel.textColor = [UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1];
    phonelabel.font = [UIFont systemFontOfSize:fontsize-4];
    phonelabel.textAlignment = NSTextAlignmentCenter;
    NSString * phonestring = [[NSUserDefaults standardUserDefaults]objectForKey:USERDEFAULTS_PHONE];
    NSString * phonehidestr1 = [phonestring substringToIndex:3];
    NSString * phonehidestr2 = [phonestring substringFromIndex:phonestring.length-4];
    phonelabel.text = [NSString stringWithFormat:@"短信验证码已发送至%@****%@,请注意查收",phonehidestr1,phonehidestr2];
    UIView * firstview = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(phonelabel.frame), SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    firstview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:firstview];
    yanzhengtf = [[UITextField alloc]initWithFrame:CGRectMake(23.0/W_BASE*SCREEN_W, CGRectGetMaxY(phonelabel.frame), 250.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    yanzhengtf.placeholder = @"短信验证码";
    yanzhengtf.font = [UIFont systemFontOfSize:fontsize-3];
    yanzhengtf.delegate = self;
    yanzhengtf.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:yanzhengtf];
    [yanzhengtf becomeFirstResponder];
    
    //重新发送验证码
    resetyanzhengbtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_W - 185.0/W_BASE*SCREEN_W, CGRectGetMaxY(phonelabel.frame)+15.0/H_BASE*SCREEN_H,160.0/W_BASE*SCREEN_W, 50.0/H_BASE*SCREEN_H)];
    resetyanzhengbtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [resetyanzhengbtn setTitleColor:[UIColor colorWithRed:47/255.0 green:147/255.0 blue:258/255.0 alpha:1] forState:UIControlStateNormal];
    resetyanzhengbtn.titleLabel.font = [UIFont systemFontOfSize:fontsize-4];
    [resetyanzhengbtn  setTitle:@"已发送(60s)" forState:UIControlStateNormal];
    [self.view addSubview:resetyanzhengbtn];
    [resetyanzhengbtn addTarget:self action:@selector(AgainYanzheng) forControlEvents:UIControlEventTouchUpInside];
    resetyanzhengbtn.layer.borderWidth = 1;
    resetyanzhengbtn.backgroundColor = COLORRGBA(239, 239, 239, 1);
    resetyanzhengbtn.layer.cornerRadius  = fontsize - 6;
    resetyanzhengbtn.layer.borderColor = [COLORRGBA(239, 239, 239, 1)CGColor];
    resetyanzhengbtn.clipsToBounds = YES;
    
    
    nextbtn = [[UIButton alloc]initWithFrame:CGRectMake(25.0/W_BASE*SCREEN_W, CGRectGetMaxY(yanzhengtf.frame)+66.0/H_BASE*SCREEN_H,SCREEN_W- 50.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    nextbtn.backgroundColor = COLORRGBA(59, 214, 117, 0.5);
    [nextbtn setTitle:@"下一步" forState:UIControlStateNormal];
    nextbtn.layer.cornerRadius = 2;
    nextbtn.titleLabel.font = [UIFont systemFontOfSize:fontsize];
    [self.view addSubview:nextbtn];
    nextbtn.tag = next_tag;
    [nextbtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    nextbtn.userInteractionEnabled = NO;

    [self loadTimer];
    

}

- (void)loadTimer{
    
    __block NSInteger time = 60; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [resetyanzhengbtn setTitle:@"重新发送" forState:UIControlStateNormal];
                
                [resetyanzhengbtn setTitleColor:[UIColor colorWithRed:47/255.0 green:147/255.0 blue:258/255.0 alpha:1] forState:UIControlStateNormal];
                
                resetyanzhengbtn.userInteractionEnabled = YES;
                
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [resetyanzhengbtn setTitle:[NSString stringWithFormat:@"已发送(%2ds)", seconds] forState:UIControlStateNormal];
                [resetyanzhengbtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                
                resetyanzhengbtn.userInteractionEnabled = NO;
            });
            time--;
            
        }
    });
    
    dispatch_resume(_timer);
    
    
}

#pragma mark - - - - - - - - - - -  Action - - - - - - - - - - - - -
- (void)enterClick:(UIButton *)btn{
    
    switch (btn.tag) {
        case return_tag:
            //返回
            [self.navigationController popViewControllerAnimated:YES];
            break;
        case next_tag:
            //下一步
        {
            [self.view endEditing:YES];
            ZhifuPass2ViewController * nextvc = [[ZhifuPass2ViewController alloc]init];
            nextvc.code  = yanzhengtf.text;
            [self.navigationController pushViewController:nextvc animated:YES];
            break;
        }
              default:
            break;
            
    }
}
#pragma mark ---- TEXTfileld Delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    NSString * teststring = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    if (teststring.length >= 6) {
        
        nextbtn.backgroundColor = COLORRGBA(59, 214, 117, 1);
        nextbtn.userInteractionEnabled = YES;
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self.view endEditing:YES];
    
    return YES;
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [yanzhengtf resignFirstResponder];
    
    
}

- (void)stopTimer{
    
    // 页面消失时，终止定时器
    
    //终止定时器
    if (_timer) {
        
        dispatch_source_cancel(_timer);
        
    }
    
    
    //改变view.btn 的字样及颜色
    NSLog(@"消失界面更改");
    
    [resetyanzhengbtn setTitle:@"重新发送验证码" forState:UIControlStateNormal];
    
    resetyanzhengbtn.layer.borderColor = [UIColor colorWithRed:238/255.0 green:240/255.0 blue:239/255.0 alpha:1].CGColor;
    
    
}

#pragma mark --------------------------重新发送验证码----------------
- (void)AgainYanzheng{
    
    [self loadTimer];
    //重新发送接口
    NSString * phone = [[NSUserDefaults standardUserDefaults]objectForKey:USERDEFAULTS_PHONE];
    [self getCode1:phone];

}

#pragma mark - - - - --------获取支付验证码 － － － － －－ － － － －－ － －
- (void)getCode1:(NSString * )phonestr{
    
    
    
    //开始动画
    UIImageView * im = [PublicMethod startAnimation];
    
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    
    NSString * token = [user objectForKey:USER_TOCKE];
    
    NSString * url = [NSString stringWithFormat:@"%@&token=%@",URL_ZHIFUGECODE,token];
    NSLog(@"获取支付密码url %@",url);
    [self.manger GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if (responseObject) {
            
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            NSInteger code = [dict[@"code"]integerValue];
            
            if (code == 0) {
                
                //获取验证码成功
                
                [im stopAnimating];
                
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
                //进入修改支付密码界面
                
                ZhifuPass1ViewController * zhifupass = [[ZhifuPass1ViewController alloc]init];
                [self.navigationController pushViewController:zhifupass animated:YES];
            }else{
                
                [im stopAnimating];
                
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
                
            }
            
            
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [im stopAnimating];
        
        ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
        
    }];
    
    
}

- (AFHTTPSessionManager*)manger{
    
    _manger = [AFHTTPSessionManager manager];
    
    _manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    _manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
    
    return _manger;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
